package com.example.gateway.filter;

import cn.hutool.core.collection.ListUtil;
import com.example.gateway.config.GatewayProperties;
import com.example.gateway.constant.Ordered;
import com.example.gateway.exception.DemoEnvForbiddenException;
import com.example.starter.util.AntPathUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author 王令
 * @since 2022/9/23 11:09
 */
@Order(Ordered.DEMO_DEV)
@RequiredArgsConstructor
@Configuration
@ConditionalOnProperty(prefix = "com.example.gateway.demo-env", name = "enabled", havingValue = "true")
public class DemoEnvGlobalFilter implements GlobalFilter {

    private static final List<String> demoEnvForbiddenMethod = ListUtil.of("POST", "PUT", "DELETE");

    private final GatewayProperties properties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String method = request.getMethodValue();
        String uri = request.getURI().getPath();
        GatewayProperties.DemoEnv demoEnv = properties.getDemoEnv();
        if (demoEnvForbiddenMethod.contains(method)
                && !AntPathUtil.matches(demoEnv.getPermitUrls(), uri)) {
            throw new DemoEnvForbiddenException();
        }
        return chain.filter(exchange);
    }
}
